package com.basic.common.handler;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.basic.modules.sys.entity.SysUserEntity;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;

@Component
public class MybatisHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", DateUtil.date(), metaObject);
        this.setFieldValByName("updateTime", DateUtil.date(), metaObject);
        Object object = SecurityUtils.getSubject().getPrincipal();
        if (ObjectUtil.isNotEmpty(object)) {
            SysUserEntity sysUser = (SysUserEntity) object;
            this.setFieldValByName("createUserId", sysUser.getUserId(), metaObject);
            this.setFieldValByName("createUserName", sysUser.getName(), metaObject);
            this.setFieldValByName("updateUserId", sysUser.getUserId(), metaObject);
            this.setFieldValByName("updateUserName", sysUser.getName(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", DateUtil.date(), metaObject);
        Object object = SecurityUtils.getSubject().getPrincipal();
        if (ObjectUtil.isNotEmpty(object)) {
            SysUserEntity sysUser = (SysUserEntity) object;
            this.setFieldValByName("updateUserId", sysUser.getUserId(), metaObject);
            this.setFieldValByName("updateUserName", sysUser.getName(), metaObject);
        }
    }
}
